<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.png">
  <link rel="mask-icon" href="/images/avatar.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notes.maxwi.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":true,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="主要是记录Java中与C++不同的地方，快速浏览，参考书是《Java核心技术 卷I》Java 8 SE API：https:&#x2F;&#x2F;docs.oracle.com&#x2F;javase&#x2F;8&#x2F;docs&#x2F;api&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="Java学习笔记之面向对象">
<meta property="og:url" content="http://notes.maxwi.com/2016/11/03/java-study-notes-oop/index.html">
<meta property="og:site_name" content="blueyi&#39;s notes">
<meta property="og:description" content="主要是记录Java中与C++不同的地方，快速浏览，参考书是《Java核心技术 卷I》Java 8 SE API：https:&#x2F;&#x2F;docs.oracle.com&#x2F;javase&#x2F;8&#x2F;docs&#x2F;api&#x2F;">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2016-11-03T11:33:32.000Z">
<meta property="article:modified_time" content="2016-11-03T11:33:32.000Z">
<meta property="article:author" content="blueyi">
<meta property="article:tag" content="notes">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://notes.maxwi.com/2016/11/03/java-study-notes-oop/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>Java学习笔记之面向对象 | blueyi's notes</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="blueyi's notes" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="blueyi's notes" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">blueyi's notes</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Follow Excellence,Success will chase you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://notes.maxwi.com/2016/11/03/java-study-notes-oop/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/default_avatar.jpg">
      <meta itemprop="name" content="blueyi">
      <meta itemprop="description" content="心怀善意，虛怀若谷！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="blueyi's notes">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java学习笔记之面向对象
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2016-11-03 19:33:32" itemprop="dateCreated datePublished" datetime="2016-11-03T19:33:32+08:00">2016-11-03</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>11k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>10 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>主要是记录Java中与C++不同的地方，快速浏览，参考书是《Java核心技术 卷I》<br>Java 8 SE API：<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/8/docs/api/">https://docs.oracle.com/javase/8/docs/api/</a></p>
<span id="more"></span>
<p>1.Java中，任何对象变量的值都是对存储在另外一个地方的一个对象的引用，也就是说Java中的对象实现上并不包含其对象本身，而只是指向一个别处的对象，类似于C++中的对象指针，与C++中的引用不同，C++中引用不能被赋值，创建时必须初始化。如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Date birthday;   <span class="comment">//java</span></span><br></pre></td></tr></table></figure>
<p>类似于C++中的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Date *birthday;  <span class="comment">//c++</span></span><br></pre></td></tr></table></figure>
<p>而java中的对象可以只创建不初始化，而在创建后使用new进行初始化，或者将其赋值为null。当然不初始化之类的变量无法使用。</p>
<h2 id="Java内置类"><a href="#Java内置类" class="headerlink" title="Java内置类"></a>Java内置类</h2><p>2.Java类库中包含了大量实用的类，例如表示日期和时间的GregorianCalendar类（java.util.GregorianCalendar）。Date类表示一个特定的时间，即用距离一个固定时间（纪元 1970,01,01,00:00:00）的毫秒数表示。而GregorianCalendar类是用日历表示时间，一个<code>new GregorianCalendar()</code>对象表示对象构造时的日期和时间，或者表示某个特定的日期：<code>new GregorianCalendar(1999,11,31);//表示12月，因为月份从0开始</code>，或者使用常量并将其存储在对象变量中：<code>GregorianCalendar deadline = new GregorianCalendar(1999, Calendar.DECEMBER, 32, 23, 59, 59);</code></p>
<p>3.GregorianCalendar类中包含了大量用于操作日期和时间的函数，其中get方法和set方法是最常用的，分别用于获取和设置其对象中的相应时间值，包括年、月、日，而Calendar类中定义了一些日期相关的常量，可用于表达希望从GregorianCalendar对象中的项，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">GregorianCalendar</span> <span class="variable">now</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GregorianCalendar</span>();</span><br><span class="line"><span class="type">int</span> <span class="variable">month</span> <span class="operator">=</span> now.get(Calendar.MONTH);  <span class="comment">//获取月份</span></span><br><span class="line"><span class="type">int</span> <span class="variable">weekday</span> <span class="operator">=</span> now.get(Calendar.DAY_OF_WEEK);  <span class="comment">//获取周天</span></span><br><span class="line"><span class="comment">//使用set</span></span><br><span class="line">now.set(Calendar.YEAR, <span class="number">2016</span>);</span><br><span class="line">now.set(Calendar.MONTH, Calendar.APRIL);</span><br><span class="line">now.set(Calendar.DAY_OF_MONTH, <span class="number">15</span>);</span><br><span class="line"><span class="comment">//使用add来为日期增加天数</span></span><br><span class="line">now.add(Calendar.MONTH, <span class="number">6</span>);  <span class="comment">//当时日期向后移6个月，可以是负数，表示前移</span></span><br></pre></td></tr></table></figure>

<p>java中类似get仅访问实例域而不进行修改的方法称为访问器方法（accessor method），类似set的对实例域做出修改的方法称为更改器方法（mutator method）。类似C++中带有const后缀的方法是访问器方法，默认为更改器方法。但java中这两类方法语法上没有明显区别。通过的习惯是访问器方法名前面加上前缀get，更改器方法前面加上前缀set，例如</p>
<p>4.GregorianCalendar类的getTime方法和setTime方法，可以用来获得和设置日历对象所表示的时间点，利用它们可以实现Date类内容与GregorianCalendar类的转换，因为Date类不知道如何操作日历。例如，假定已知年、月、日并希望创建一个包含这个时间值的Date对象，就可以先创建一个GregorianCalendar对象，然后调用getTime方法获得Date对象时间：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通过年、月、日创建Date对象</span></span><br><span class="line"><span class="type">GregorianCalendar</span> <span class="variable">calendar</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GregorianCalendar</span>(year, month, day);</span><br><span class="line"><span class="type">Date</span> <span class="variable">time</span> <span class="operator">=</span> clanedar.getTime();</span><br><span class="line"><span class="comment">//获取Date对象中的年、月、日</span></span><br><span class="line">calendar.setTime(time);</span><br><span class="line"><span class="type">int</span> <span class="variable">year</span> <span class="operator">=</span> calendar.get(Calendar.YEAR);</span><br></pre></td></tr></table></figure>

<p>5.下面这个例子将打印输出当前月的日历，支持指定以周几为一周的第一天，并在当前日期后面加个*号标记：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;  <span class="comment">//用于输出及时间相关类</span></span><br><span class="line"><span class="keyword">import</span> java.text.DateFormatSymbols;  <span class="comment">//用于获取时间格式的字符串表示形式</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CalendarTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//Locale.setDefault(Locale.CHINA);  //设置地区为中国，这样会以星期-、星期二...的方式显示</span></span><br><span class="line">        <span class="comment">//创建当前日期</span></span><br><span class="line">        <span class="type">GregorianCalendar</span> <span class="variable">d</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GregorianCalendar</span>();</span><br><span class="line">        <span class="type">int</span> <span class="variable">today</span> <span class="operator">=</span> d.get(Calendar.DAY_OF_MONTH);</span><br><span class="line">        <span class="type">int</span> <span class="variable">month</span> <span class="operator">=</span> d.get(Calendar.MONTH);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//将日期设置为当月的第一天，并获取这一天为周几</span></span><br><span class="line">        d.set(Calendar.DAY_OF_MONTH, <span class="number">1</span>);</span><br><span class="line">        <span class="type">int</span> <span class="variable">weekday</span> <span class="operator">=</span> d.get(Calendar.DAY_OF_WEEK);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//获取当前时区下每周的第一天为周几</span></span><br><span class="line">        <span class="comment">//int firstDayOfWeek = d.getFirstDayOfWeek();  //根据地区设定</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">firstDayOfWeek</span> <span class="operator">=</span> <span class="number">2</span>;  <span class="comment">//强制修改为周一为第一天</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//确定打印日历的第一行所需要的缩进</span></span><br><span class="line">        <span class="comment">//通过将当前日期减-1，直到当前日期为本周的第一天停止</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">indent</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> (weekday != firstDayOfWeek)</span><br><span class="line">        &#123;</span><br><span class="line">            indent++;</span><br><span class="line">            d.add(Calendar.DAY_OF_MONTH, -<span class="number">1</span>);</span><br><span class="line">            weekday = d.get(Calendar.DAY_OF_WEEK);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//打印第一行的周名称</span></span><br><span class="line">        <span class="comment">//此时d中存储的周日期即为本周的第一天，所以通过将其日期加1，逐个打印即可</span></span><br><span class="line">        String[] weekdayNames = <span class="keyword">new</span> <span class="title class_">DateFormatSymbols</span>().getShortWeekdays();  <span class="comment">//获取一周的每天的缩写</span></span><br><span class="line">        <span class="keyword">do</span> </span><br><span class="line">        &#123;</span><br><span class="line">            System.out.printf(<span class="string">&quot;%4s&quot;</span>, weekdayNames[weekday]);   <span class="comment">//每个周名称占4个字符空间</span></span><br><span class="line">            d.add(Calendar.DAY_OF_MONTH, <span class="number">1</span>);</span><br><span class="line">            weekday = d.get(Calendar.DAY_OF_WEEK);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (weekday != firstDayOfWeek);</span><br><span class="line">        System.out.println();</span><br><span class="line">        <span class="comment">//打印日期</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; indent; ++i)</span><br><span class="line">            System.out.print(<span class="string">&quot;    &quot;</span>);</span><br><span class="line">        d.set(Calendar.DAY_OF_MONTH, <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">do</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">day</span> <span class="operator">=</span> d.get(Calendar.DAY_OF_MONTH);</span><br><span class="line">            System.out.printf(<span class="string">&quot;%3d&quot;</span>, day);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//将当前日期后面使用*标记</span></span><br><span class="line">            <span class="keyword">if</span> (day == today) System.out.print(<span class="string">&quot;*&quot;</span>);</span><br><span class="line">            <span class="keyword">else</span> System.out.print(<span class="string">&quot; &quot;</span>);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//将日期指向下一天</span></span><br><span class="line">            d.add(Calendar.DAY_OF_MONTH, <span class="number">1</span>);</span><br><span class="line">            weekday = d.get(Calendar.DAY_OF_WEEK);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//新的一周开始时换行</span></span><br><span class="line">            <span class="keyword">if</span> (weekday == firstDayOfWeek) System.out.println();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (d.get(Calendar.MONTH) == month);  <span class="comment">//当月份变成下个月时退出循环</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//如果最后当前d中的日期不是一周的第一天，则需要换行</span></span><br><span class="line">        <span class="keyword">if</span> (weekday != firstDayOfWeek) System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.java.util.GregorianCalendar的API中包含大量日期时间相关的方法，java.text.DateFormatSymbols包的API中包含很多关于日期的字符串表示形式，如获得当前地区的星期几或月份的名称缩写等：<code>String[] getShortWeekdays(); String[] getShortMonths()</code></p>
<h2 id="自定义类"><a href="#自定义类" class="headerlink" title="自定义类"></a>自定义类</h2><p>1.java中文件名必须与public修饰的类名相同，一个文件中只能有一个public类，但可以有任意数目非公有类。如果将2个类放在不同的文件中，且公有类使用了另一个类，例如文件名都有前缀Employ，则可以这样编译：<code>javac Employ*.java</code>。或者直接使用javac编译那个公有类，当时java编译器发现这个类引用了另一个类时，会去查找其class文件，如果没有找到，或者发现其java文件较已有的class文件版本新，java编译器就会自动地重新编译这个文件。使用java解释器运行时，只需指定带有main方法的公有类的class文件即可。<br>当一个文件中有两个不同的类的时候，编译之后会生成两个类名的class文件，将带有main方法的class传递给java解释器运行即可。如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">EmployeeTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Employee</span> <span class="variable">blueyi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Employee</span>(<span class="string">&quot;blueyi&quot;</span>, <span class="number">27</span>);</span><br><span class="line">        System.out.println(blueyi.getName() + <span class="string">&quot; : &quot;</span> + blueyi.getAge());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">age</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Employee</span><span class="params">(String n, <span class="type">int</span> a)</span>  <span class="comment">//构造函数</span></span><br><span class="line">    &#123;</span><br><span class="line">        name = n;</span><br><span class="line">        age = a;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span></span><br><span class="line">    &#123;</span><br><span class="line">       <span class="keyword">return</span> name; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAge</span><span class="params">()</span></span><br><span class="line">    &#123;</span><br><span class="line">       <span class="keyword">return</span> age; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编译之后将会有一个EmployeeTest.class文件和Employee.class文件</p>
<p>2.Java构造器的工作方式与C++一样，但java中的对象都是在堆中构造的，所以必须与new操作符一起使用。不能在构造器中定义与实例域重名的局部变量。</p>
<p>3.java中类方法的第一个参数也是隐的this，但这个this是类对象，而不是指针。java的所有类方法都必须在类的内部定义，而不能像C++那个类外定义。</p>
<p>4.不要编写返回引用可变对象的访问器方法，由于java中返回的对象默认是引用，所以使用访问器返回的引用会修改原私有数据，可以通过返回克隆的方法进行数据域的拷贝，这样就可以保护原对象中的私有数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">public</span> Date <span class="title function_">getHireDay</span><span class="params">()</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">return</span> hireDay.clone();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>方法可以访问所属类的所有对象的私有数据</p>
<p>5.final实例域，可以使用final修鉓类中的实例域，被final修饰的数据必须在构造器中设置，并且在后面的操作中不能对它修改，final修饰符大都应用于基本（primitive）类型域，或不可变（immutable）类的域，如String类，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">final</span> String name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.java中的static作用与C++中的类似，表示属于类且不属于类对象的变量和方法。由于static方法没有隐式的this对象，所以不能方法对象的非static方法及数据，但可以访问该类的其他static域。static方法调用与C++不同的是直接使用.运算符，而不是::，如：<code>Math.pow</code></p>
<p>7.可以通过为每一个类添加一个main方法用于单元测试该类的功能，例如StaticTest类名与文件名相同，其中又包含了一个名为Employee的类，例如两个类中都有main方法，那么运行：<code>java Employee</code>和java StaticTest将执行两个不同的main方法。</p>
<p>8.java中的函数参数传递方式都是按值调用。只是当传递的是对象的时候，传递的是对象的引用的拷贝（即实际上还是按值传递），所以可以通过方法修改对象，但却不能修改基本数据类型的参数。实际上C++中当向函数传递一个指针的时候传递也是指针的拷贝。总结来说java中的方法参数使用情况：</p>
<ul>
<li>一个方法不能修改一个基本数据类型的参数（即数值型和布尔型）。</li>
<li>一个方法可以改变一个对象参数的状态。（即可以通过方法修改对象中的参数）</li>
<li>一个方法不能让对象参数引用一个新的对象。（即不能通过向方法传递2个对象来交换它们）</li>
</ul>
<p>9.Java支持函数重载，如果类的域没有在构造器中显式地赋予初值，则会被自动地赋为默认值：数值为0、布尔值为false、对象引用为null。但同样建议要手动进行初始值初始化。</p>
<p>10.只有当类没有提供任何构造函数时，编译器才会提供一个默认的无参数构造函数。如果提供了一个有参数的构造函数，则此时不会提供无参数的构造函数，调用new创建对象调用无参数数构造器时就会在编译时报错。</p>
<p>11.Java中会在执行构造器之前，先执行赋值操作，所以可以通过下面的方式对域进行初始化：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span> nextId;</span><br><span class="line">  <span class="keyword">private</span> <span class="type">int</span> <span class="variable">id</span> <span class="operator">=</span> assignId();</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">assignId</span><span class="params">()</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">r</span> <span class="operator">=</span> nextId;</span><br><span class="line">    nextId++;</span><br><span class="line">    <span class="keyword">return</span> r;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>12.构造器的实例域在命名时可以加上前缀来区分，或者实例域使用原名字，而通过在构造器的内部使用this来引用类变量的方式赋值：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">Employee</span><span class="params">(String aName, <span class="type">double</span> aSalary)</span></span><br><span class="line">&#123;</span><br><span class="line">  name = aName;</span><br><span class="line">  salary = aSalary;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//或者</span></span><br><span class="line"><span class="keyword">public</span> <span class="title function_">Employee</span><span class="params">(String name, <span class="type">double</span> salary)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="built_in">this</span>.name = name;</span><br><span class="line">  <span class="built_in">this</span>.salary = salary;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>13.可以通过this在一个构造器中调用另一个构造器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">Employ</span><span class="params">(<span class="type">double</span> s)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">//call Employee(String, double)</span></span><br><span class="line">  <span class="built_in">this</span>(<span class="string">&quot;Employee #&quot;</span> + nextId, s);</span><br><span class="line">  nextId++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>14.除了可以通过在构造器在设置值和在声明中赋值来进行初始化数据域外，还可以通过初始化块（initialization block）来构造类的对象，只要构造类的对象，这些初始化块就会被执行。如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">class Employee</span><br><span class="line">&#123;</span><br><span class="line">  private static nextId;</span><br><span class="line">  private int id;</span><br><span class="line">  private String name;</span><br><span class="line">  // object initialization block</span><br><span class="line">  &#123;</span><br><span class="line">    id = nextId;</span><br><span class="line">    nextId++;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  public Employee(String n, int i)</span><br><span class="line">  &#123;</span><br><span class="line">    name = n;</span><br><span class="line">    id = i;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>15.初始化数据域有多种途径，调用顺序如下：</p>
<ul>
<li>所有数据域被初始化为默认值：0、false或null</li>
<li>按照在类声明中出现的次序，依次执行所有域初始化语句和初始化块</li>
<li>如果构造器第一行调用了第二个构造器，则执行第二个构造器的主体</li>
<li>执行这个构造器的主体</li>
</ul>
<p>16.也可以将初始化块标记为静态域，在类的第一次加载的时候，将进行静态域的初始化：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Hello</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">static</span></span><br><span class="line">  &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;Hello, World&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行这段程序将打印输出Hello, World，而无需main方法。</p>
<p>17.java中有垃圾回收来自动处理内存回收问题，而无需析构函数，但可以添加finalize方法，finalize方法将在垃圾回收器清除对象之前调用。</p>
<h2 id="包"><a href="#包" class="headerlink" title="包"></a>包</h2><p>java中使用包（package）将类组织起来，标准的java类库分布在多个包中，包括java.lang、java.util和java.net等，都具有一个层次结构。使用包主要是确保类名的唯一性，Sun公司建议将公司的互联网域名以逆序的形式作为包名，并且对于不同的项目使用不同的子包。例如我的域名maxwi.com，逆序就是com.maxwi，如果笔记作为一个包就是com.maxwi.notes。有点类似于C++中的命名空间</p>
<h3 id="类的导入"><a href="#类的导入" class="headerlink" title="类的导入"></a>类的导入</h3><p>1.一个类可以使用所属包中的所有类，以及其他包中的公有类（public class），有两种方式使用另一包中的公有类，一种是使用完整的包名，如：<code>java.util.Date today = new java.util.Date();</code>，另一种是使用import，impot即可以一次导入一个特定的类，也可以导入整个包，import应该位于源文件的顶部，但位于package语句的后面：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*; <span class="comment">//导入java.util包中的所有的类</span></span><br><span class="line"><span class="keyword">import</span> java.util.Date;  <span class="comment">//导入Date类</span></span><br></pre></td></tr></table></figure>

<p>2.如果导入的2个包都同时含有同一个类，则会出现编译错误，可以通过添加一个特定的import来指定使用哪个类来解决：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">import</span> java.sql.*;</span><br><span class="line"><span class="keyword">import</span> java.util.Date; <span class="comment">//util和sql中都包含有类Date</span></span><br></pre></td></tr></table></figure>
<p>当需要使用sql中的类Date时，可以直接使用完整的包名来引用 </p>
<p>3.import也可以用来导入静太方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> java.lang.System.*;</span><br><span class="line">out.println(<span class="string">&quot;Hi&quot;</span>);</span><br></pre></td></tr></table></figure>

<h3 id="包的使用"><a href="#包的使用" class="headerlink" title="包的使用"></a>包的使用</h3><p>如果不手动指定文件中的类所属的包的话，会默认在default包中<br>4.想将类放入包中只需要在文件的开头使用package加上包名即可，此时要注意类文件必须在以包名指定的以.分隔的路径下，如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.maxwi.notes;  <span class="comment">//表示该类将在路径com/maxwi/notes/Employee.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编译方法是在包的根目录或者同一个目录下的其他子目录，中使用另一个java文件调用该类，然后编译这个调用类的文件即可：<br>类Employee路径com/maxwi/notes/Employee.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.maxwi.notes;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">age</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Employee</span><span class="params">(String n, <span class="type">int</span> a)</span> &#123;</span><br><span class="line">        name = n;</span><br><span class="line">        age = a;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getAge</span><span class="params">()</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> age;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>类TestEmployee所在路径：com/testEmployee/TestEmployee.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.testEmployee;</span><br><span class="line"><span class="keyword">import</span> com.maxwi.notes.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestEmployee</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Employee</span> <span class="variable">blueyi</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Employee</span>(<span class="string">&quot;blueyi&quot;</span>, <span class="number">27</span>);</span><br><span class="line">        System.out.println(blueyi.getName() + <span class="string">&quot; : &quot;</span> + blueyi.getAge());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需要从根目录编译带有main方法的类</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">javac com/testEmployee/TestEmployee.java</span><br></pre></td></tr></table></figure>
<p>运行只需要在根目录下执行带包的类名即可，解释器会自动查找目录下的class文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">java com.testEmployee.TestEmployee</span><br></pre></td></tr></table></figure>
<p>目录结构如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">E:.</span><br><span class="line">└───com</span><br><span class="line">    ├───maxwi</span><br><span class="line">    │   └───notes</span><br><span class="line">    │           Employee.class</span><br><span class="line">    │           Employee.java</span><br><span class="line">    │</span><br><span class="line">    └───testEmployee</span><br><span class="line">            TestEmployee.class</span><br><span class="line">            TestEmployee.java</span><br></pre></td></tr></table></figure>

<p>5.被public修饰的部分可以被任意的类使用，被private修饰的部分只能被定义它的类使用，而没有指定public或private的部分（类、方法或变量）可以被同一个包中的所有方法访问。</p>
<p>6.类路径必须与包名匹配，另外类文件也可以存储在JAR（Java归档）文件中，JAR文件就是包含目录结构的java文件，为了使类能够被多个程序共享，首先必须将类以包名指定的目录结构存放，或者直接是一个JAR文件中，然后将其加入到类路径（class path）中，类路径就是包含类文件的路径的集合，类路径默认不包含不当前路径，即点，所以通常也要将当前目录加入类路径。UNIX环境中类路径以:分隔，windows下以分号;分隔。在编译时通过选项<code>-classpath</code>或<code>-cp</code>来指定类路径：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">java -classpath /home/usr/classdir:.:/home/usr/archive/archive.jar  MyProg # linux系统</span><br></pre></td></tr></table></figure>
<p>或者通过设置CLASSPATH环境变量的方法来实现。</p>
<h3 id="javadoc注释"><a href="#javadoc注释" class="headerlink" title="javadoc注释"></a>javadoc注释</h3><p>可以在源文件中使用/<em>*….</em>/进行文档注释，然后使用javadoc工具生成html类型的类文档，文档注释应该放在所描述特性的前面，例如类前面，类方法前面等，注释文档中可以有以@开始的标记，如@author、@param、@return等，或者是自由格式文本，也可以包含html标签用于强调等，如<code>&lt;em&gt;...&lt;/em&gt;</code></p>
<p>类注释必须放在import语句之后，类定义之前</p>
<p>生成javadoc：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">javadoc -d docDirectory nameOfPackage  #对包生成</span><br><span class="line">javadoc -d docDirectory *.java #对java文件生成，如果省略-d docDirectory选项，会默认生成在当前目录</span><br></pre></td></tr></table></figure>

<h3 id="类设计技巧"><a href="#类设计技巧" class="headerlink" title="类设计技巧"></a>类设计技巧</h3><ul>
<li>一定要保证数据私有</li>
<li>一定要对数据初始化</li>
<li>不要在类中使用过多的基本类型</li>
<li>不是所有的域都需要独立的域访问器或域更改器</li>
<li>将职责过多的类进行分解</li>
<li>类名和方法名要能够体现它们的职责</li>
</ul>
<h2 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h2><h3 id="类与子类"><a href="#类与子类" class="headerlink" title="类与子类"></a>类与子类</h3><p>1.反射（reflection）是指在程序运行期间发现更多的类及其属性的能力。<br>2.Java中的继承是使用关键字extends代替C++中的冒号（:）。在java中，所有的继承都是公有继承，而没有C++中的私有继承和保护继承。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Manager</span> <span class="keyword">extends</span> <span class="title class_">Employee</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="type">double</span> bonus;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setBonus</span><span class="params">(<span class="type">double</span> b)</span></span><br><span class="line">  &#123;</span><br><span class="line">    bonus = b;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3.派生类不能够直接访问超类（父类）的私有域，需要借助关键字super，同样派生类的构造函数也不能直接调用超类的构造函数，需要借助super关键字。例如定义Manager的getSalary方法时需要调用其父类的方法返回值+其bonus参数后返回，则需要如下方法调用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="type">double</span> <span class="title function_">getSalary</span><span class="params">()</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">double</span> <span class="variable">baseSalary</span> <span class="operator">=</span> <span class="built_in">super</span>.getSalary(); <span class="comment">//相当于C++中的Employee::getSalary();</span></span><br><span class="line">  <span class="keyword">return</span> baseSalary + bonus;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>构造器的应用如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">Manager</span><span class="params">(String n, <span class="type">double</span> s, <span class="type">int</span> year, <span class="type">int</span> month, <span class="type">int</span> day)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="built_in">super</span>(n, s, year, month, day);</span><br><span class="line">  bonus = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>相当于C++中的：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Manager::<span class="built_in">Manager</span>(std::string n, <span class="type">double</span> s, <span class="type">int</span> year, <span class="type">int</span> month, <span class="type">int</span> day) : <span class="built_in">Employee</span>(n, s, year, month, day)</span><br><span class="line">&#123;</span><br><span class="line">  bonus = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在java中，不需要将方法声明为虚方法，动态绑定是默认发生的，即父类定义的变量可以调用子类对象中的方法。java中的对象变量都是多态的，一个父类变量即可以引用其父类对象，也可以引用其任意一个子类的任何对象。但父类的引用不能赋给子类变量（与C++的多态类似）。如果不希望让一个方法具有虚拟特征，可以将它标记为final。</p>
<p>4.final修饰的类将不允许被继承，当类中的方法被声明为final时，则该方法在子类中就不能被覆盖。final类中的所有方法都自动地被成为final方法。</p>
<p>5.可以通过instanceof运算符在进行类型转换之前测试是否可以转换：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (x <span class="keyword">instanceof</span> C)</span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">C</span> <span class="variable">ax</span> <span class="operator">=</span> (C) x;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.包含一个或多个抽象方法的类必须被声明为抽象的，类即使不含抽象方法，也可以将类声明为抽象类。抽象类不能被实例化，即使用abstract修饰的类不能创建其类对象，但可以创建一个抽象类的对象变量，并用它引用非抽象子类的对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">Person</span> <span class="comment">//抽象类</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">abstract</span> String <span class="title function_">getDescription</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">Person</span> <span class="variable">p</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Student</span>(<span class="string">&quot;blueyi&quot;</span>, <span class="number">22</span>); <span class="comment">//抽象类对象p引用其子类的对象</span></span><br></pre></td></tr></table></figure>

<p>7.Java中的访问保护：</p>
<ul>
<li>private–仅对本类可见</li>
<li>public–对所有类可见</li>
<li>protected–对本包和所有子类可见</li>
<li>默认，不加修饰符–对本包可见  </li>
</ul>
<h3 id="Object类"><a href="#Object类" class="headerlink" title="Object类"></a>Object类</h3>
    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/notes/" rel="tag"># notes</a>
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2016/10/03/java-study-notes-basic/" rel="prev" title="Java学习笔记之基础语法">
      <i class="fa fa-chevron-left"></i> Java学习笔记之基础语法
    </a></div>
      <div class="post-nav-item">
    <a href="/2016/11/29/kvm-create-and-manage/" rel="next" title="Ubuntu Server/Debian下的KVM虚拟机创建及管理详解">
      Ubuntu Server/Debian下的KVM虚拟机创建及管理详解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java%E5%86%85%E7%BD%AE%E7%B1%BB"><span class="nav-number">1.</span> <span class="nav-text">Java内置类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B1%BB"><span class="nav-number">2.</span> <span class="nav-text">自定义类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8C%85"><span class="nav-number">3.</span> <span class="nav-text">包</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E7%9A%84%E5%AF%BC%E5%85%A5"><span class="nav-number">3.1.</span> <span class="nav-text">类的导入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8C%85%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">3.2.</span> <span class="nav-text">包的使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#javadoc%E6%B3%A8%E9%87%8A"><span class="nav-number">3.3.</span> <span class="nav-text">javadoc注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E8%AE%BE%E8%AE%A1%E6%8A%80%E5%B7%A7"><span class="nav-number">3.4.</span> <span class="nav-text">类设计技巧</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%A7%E6%89%BF"><span class="nav-number">4.</span> <span class="nav-text">继承</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E4%B8%8E%E5%AD%90%E7%B1%BB"><span class="nav-number">4.1.</span> <span class="nav-text">类与子类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Object%E7%B1%BB"><span class="nav-number">4.2.</span> <span class="nav-text">Object类</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="blueyi"
      src="/images/default_avatar.jpg">
  <p class="site-author-name" itemprop="name">blueyi</p>
  <div class="site-description" itemprop="description">心怀善意，虛怀若谷！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">104</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/blueyi" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;blueyi" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://maxwi.com/" title="http:&#x2F;&#x2F;maxwi.com" rel="noopener" target="_blank">Maxwi</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2014 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">blueyi</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">750k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">11:22</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '0f8243eb2c8b2207980f',
      clientSecret: 'd159633a33519d3b7a48b0ca729032f7d1f38a41',
      repo        : 'notes',
      owner       : 'blueyi',
      admin       : ['blueyi'],
      id          : 'a89c51e2d3491c050ed3d5b571a460e8',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

    </div>
</body>
</html>
